package com.zhy.sunmi.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import POSAPI.POSUSBAPI;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import POSSDK.POSSDK;

import com.google.gson.Gson;
import com.hjq.xtoast.XToast;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.zhy.greendao.gen.CouponsDao;
import com.zhy.greendao.gen.GoodsCateDao;
import com.zhy.greendao.gen.GoodsDao;
import com.zhy.greendao.gen.SellGoodHistoryDao;
import com.zhy.greendao.gen.SpStaffDao;
import com.zhy.greendao.gen.UserDao;
import com.zhy.sunmi.MyApplication;
import com.zhy.sunmi.R;
import com.zhy.sunmi.bean.Goods;
import com.zhy.sunmi.bean.SellGoodHistory;
import com.zhy.sunmi.bean.SpStaff;
import com.zhy.sunmi.utils.ScreenUtils;
import com.zhy.sunmi.utils.network.ProgressSubscriber;
import com.zhy.sunmi.utils.network.RetrofitUtil;

import java.util.List;

import static com.zhy.sunmi.MyApplication.interface_usb;
import static com.zhy.sunmi.MyApplication.pos_usb;

/**
 * @author zhouhongyang
 */
public class LoginActivity extends AppCompatActivity {
    private EditText editTextUserName;
    private EditText editTextPassWord;
    private Button buttonLogin;
    private SpStaffDao spStaffDao;
    private GoodsCateDao goodsCateDao;
    private GoodsDao goodsDao;
    private CouponsDao couponsDao;
    private UserDao userDao;
    private String api_token = null;
    private SellGoodHistoryDao sellGoodHistoryDao = MyApplication.getDaoSession().getSellGoodHistoryDao();


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initFullScreen();

//        PermissionX.init(LoginActivity.this)
//                .permissions(Manifest.permission.READ_CONTACTS, Manifest.permission.CAMERA, Manifest.permission.CALL_PHONE)
//                .request {
//            allGranted, grantedList, deniedList -> if (allGranted) {
//                Toast.makeText(this, "All permissions are granted", Toast.LENGTH_LONG).show();
//            } else {
//                Toast.makeText(this, "These permissions are denied: $deniedList", Toast.LENGTH_LONG).show();
//            }
//        }

        PermissionX.init(LoginActivity.this).permissions(Manifest.permission.READ_PHONE_STATE)
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, @NonNull  List<String> grantedList, @NonNull  List<String> deniedList) {
                        if (allGranted) {
//                            Toast.makeText(LoginActivity.this, "All permissions are granted", Toast.LENGTH_LONG).show();
                        } else {
//                            Toast.makeText(LoginActivity.this, "These permissions are denied: $deniedList", Toast.LENGTH_LONG).show();
                        }
                    }
                });



        setContentView(R.layout.activity_login);
        spStaffDao = MyApplication.getDaoSession().getSpStaffDao();
        goodsCateDao = MyApplication.getDaoSession().getGoodsCateDao();
        goodsDao = MyApplication.getDaoSession().getGoodsDao();
        couponsDao = MyApplication.getDaoSession().getCouponsDao();
        userDao = MyApplication.getDaoSession().getUserDao();
        initView();
        initDbData();
    }

    public static String getSN() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Build.getSerial();
        } else{
            return Build.SERIAL;
        }
    }

    private void initView() {
        editTextPassWord = findViewById(R.id.et_password);
        editTextUserName = findViewById(R.id.et_username);
        buttonLogin = findViewById(R.id.bt_login);
        String a = getSN();
//        a = "DA04215T40075";
//        System.out.println(a);
//        Toast.makeText(LoginActivity.this, a, Toast.LENGTH_LONG).show();

        getToken(a);

        buttonLogin.setOnClickListener(v -> {

            if (pos_usb == null) {
                interface_usb = new POSUSBAPI(getApplication());
                int as = interface_usb.OpenDevice();
                if (as == 1000) {

                    pos_usb = new POSSDK(interface_usb);

                } else {
                    return;
                }
            }
//            getCoupons2(api_token);
//            return;

//
//            List<Goods> goodsList = goodsDao.queryBuilder().where(GoodsDao.Properties.Hot_goods.eq("true")).list();
//            List<Goods> goodsList2 = goodsDao.queryBuilder().where(GoodsDao.Properties.No_discount.eq("true")).list();


            String username = editTextUserName.getText().toString();
//            String password = editTextPassWord.getText().toString();
            if (TextUtils.isEmpty(username)) {
                Toast.makeText(LoginActivity.this, "The user name cannot be empty", Toast.LENGTH_SHORT).show();
                return;
            }
//            if (TextUtils.isEmpty(password)) {
//                Toast.makeText(LoginActivity.this, "", Toast.LENGTH_SHORT).show();
//                return;
//            }

            List<SpStaff> spStaffs = MyApplication.getDaoSession().getSpStaffDao().queryBuilder().where(SpStaffDao.Properties.Staff_code.eq(username)).list();
            long l = spStaffs.size();
            if (l > 0) {

                MyApplication.UserName = spStaffs.get(0).getName();
                MyApplication.UserId = spStaffs.get(0).getId();
                MyApplication.postion = spStaffs.get(0).getPosition();

                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                finish();
                if (api_token != null) {

                }


            } else {
                new XToast<>(this)
                        .setDuration(1000)
                        .setContentView(R.layout.toast_hint)
                        .setAnimStyle(android.R.style.Animation_Activity)
                        .setImageDrawable(android.R.id.icon, R.mipmap.ic_dialog_tip_error)
                        .setText(android.R.id.message, "username is error")
                        .show();
//                Toast.makeText(LoginActivity.this, "username is error", Toast.LENGTH_SHORT).show();
            }


        });
    }

    void getCoupons2(String api_token) {
        SellGoodHistory sellGoodHistory = sellGoodHistoryDao.loadAll().get(0);
        sellGoodHistory.getSoldGoodDetails();


        Gson gson = new Gson();
        String as = gson.toJson(sellGoodHistory);

        RetrofitUtil.getInstance().getCoupons2(new ProgressSubscriber<>(a -> {


        }, this), api_token, as);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initFullScreen() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        // 部分机型的statusbar会有半透明的黑色背景
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // SDK21
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        //设置状态栏文字颜色
//        setAndroidNativeLightStatusBar(this,true);
        View decor = this.getWindow().getDecorView();

        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

    }

    void initDbData() {
//        spStaffDao.deleteAll();
//        SpStaff spStaff=new SpStaff((long)1,"zhy","15636085089","10","21","true","12345678");
//        spStaffDao.insert(spStaff);
//        spStaffDao.insertOrReplaceInTx();


    }

    void getToken(String machineSN) {
        RetrofitUtil.getInstance().getToken(new ProgressSubscriber<>(authorityResponseModel -> {
            MyApplication.api_token = authorityResponseModel.Data.getApi_token();
            api_token = authorityResponseModel.Data.getApi_token();
            MyApplication.MachineId = authorityResponseModel.Data.getId();
            MyApplication.getInstance().saveMachineId(authorityResponseModel.Data.getId());
            getSpStaff(api_token);
            getCoupons(api_token);
            getUsers(api_token);

//            Toast.makeText(this,authorityResponseModel.Data.getApi_token(),Toast.LENGTH_SHORT).show();

        }, this), machineSN);
    }

    void getSpStaff(String api_token) {
        RetrofitUtil.getInstance().getSpStaff(new ProgressSubscriber<>(spStaffResponseModel -> {
            spStaffDao.deleteAll();
            spStaffDao.insertInTx(spStaffResponseModel.Data);
            getGoodsCate(api_token);
//            spStaffDao.insertOrReplaceInTx(spStaffResponseModel.Data);
        }, this), api_token);
    }


    void getUsers(String api_token) {
        RetrofitUtil.getInstance().getUsers(new ProgressSubscriber<>(users -> {
            userDao.deleteAll();
            userDao.insertInTx(users.Data);
        }, this), api_token);
    }

    void getGoodsCate(String api_token) {
        RetrofitUtil.getInstance().getGoodsCate(new ProgressSubscriber<>(goodsCate -> {
            goodsCateDao.deleteAll();
            goodsCateDao.insertInTx(goodsCate.Data);
//            spStaffDao.insertOrReplaceInTx(spStaffResponseModel.Data);
            getGoods(api_token);
        }, this), api_token);
    }

    void getGoods(String api_token) {
        RetrofitUtil.getInstance().getGoods(new ProgressSubscriber<>(goods -> {
            goodsDao.deleteAll();
            goodsDao.insertInTx(goods.Data);
//            spStaffDao.insertOrReplaceInTx(spStaffResponseModel.Data);
        }, this), api_token);
    }

    void getCoupons(String api_token) {
        RetrofitUtil.getInstance().getCoupons(new ProgressSubscriber<>(coupons -> {
            couponsDao.deleteAll();
            couponsDao.insertInTx(coupons.Data);
//            spStaffDao.insertOrReplaceInTx(spStaffResponseModel.Data);
        }, this), api_token);
    }


}